<template>
  <div class="chart-wrapper">
    <h3>库存和销量分析</h3>
    <div class="circles-container">
      <div v-for="(item, index) in circleData" :key="index" class="circle-item">
        <v-chart class="circle-chart" :option="getCircleOption(item, index)" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import type { EChartsOption } from 'echarts'
import http from '../http.js'

use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent
])

const colors = ['#00FF00', '#FFD700', '#FF6B6B', '#9D4EDD', '#4B79E5']
const circleData = ref<any[]>([])

onMounted(async () => {
  // 1. 请求数据
  const res = await http.get('/stock.json')
  // 2. 取前5个商品
  circleData.value = res.slice(0, 5)
})

const getCircleOption = (item: any, idx: number): EChartsOption => ({
  title: {
    text: item.name,
    subtext: item.sales.toString(),
    left: 'center',
    top: '30%',
    itemGap:4,
    textStyle: {
      fontSize: 5,
      color: '#fff',
      fontWeight: 'normal'
    },
    subtextStyle: {
      fontSize: 8,
      color: '#fff',
      fontWeight: 'bold'
    }
  },
  series: [
    {
      type: 'pie',
      radius: ['80%', '90%'],
      avoidLabelOverlap: false,
      label: { show: false },
      emphasis: { disabled: true },
      data: [
        {
          value: item.sales,
          itemStyle: { color: colors[idx % colors.length] }
        },
        {
          value: Math.max(item.stock, 1), // 避免全满
          itemStyle: { color: 'rgba(255,255,255,0.1)' }
        }
      ]
    }
  ]
})
</script>

<style scoped>
.chart-wrapper {
  width: 100%;
  height: 100%;
  padding: 12px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

h3 {
  color: #fff;
  font-size: 16px;
  margin: 0 0 10px 0;
  padding-left: 10px;
}

.circles-container {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 10px;
  padding: 10px;
}

.circle-item {
  width: 100%;
  height: 100%;
  min-height: 0;
}

.circle-chart {
  width: 100%;
  height: 100%;
}

/* 调整最后一行的布局 */
.circle-item:nth-last-child(-n+2) {
  grid-column: span 1;
  transform: translateX(50%);
}
</style>
